import React from 'react';
import Header from './components/header';
import { pages, componentClassify, classify2CN } from './config';
import './styles/base.scss';
import './styles/code.scss';
import './styles/icons.scss';
import Markdown from './libs/markdown';
import { Accordion } from '../src';
import { Text } from '../src/components/text';

export default class App extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      page: document.location.hash.split('/')[1] || 'readme',
      defaultActive: this.getDefaultActiveKey(),
      isMenuShow: false,
    };
    this.getDefaultActiveKey = this.getDefaultActiveKey.bind(this);
    this.onPanelClick = this.onPanelClick.bind(this);
    this.toggleMenu = this.toggleMenu.bind(this);
  }

  componentWillMount() {
    window.addEventListener("hashchange", () => {
      window.scrollTo(0, 0);
      // 因为是动态生成的示例，会导致弹层不能正确卸载
      // 所以手动清理
      while(document.body.lastElementChild.tagName === 'DIV' && document.body.lastElementChild.id !== 'app') {
        document.body.lastElementChild.remove();
      }
      this.setPage();
    }, false);
  }

  getDefaultActiveKey() {
    const title = document.location.hash.split('/')[1];
    let result = 'README';
    Object.keys(pages).map(category => {
      return (
        Object.keys(pages[category]).map(items => {
          if (items === title) {
            return result = category;
          }
        })
      )
    });
    console.log('getDefaultActiveKey', result);
    return result;
  }

  getPage() {
    const routes = location.hash.match(/(?:\/(.+))?\/(.+)/);
    return routes[2];
  }

  setPage(fn) {
    this.setState({ page: this.getPage() }, fn);
  }

  getComponent(page) {
    let result;
    Object.keys(pages).map(category => {
      return (
        Object.keys(pages[category]).map(items => {
          if (items === page) {
            return result = pages[category][page];
          }
        })
      )
    })
    if (result) {
      const Doc = class extends Markdown {
        document() {
          return result.document;
        }
      }
      return React.createElement(Doc, {});
    }
  }

  dealTitleConfig(title) {
    const titleArr = title.split('-');
    if (titleArr.length === 1) {
      return <Text type="smallTitle" bold>{title}</Text>;
    } else {
      const english = titleArr[0];
      const chinese = titleArr[1];
      return (
        <div>
          <Text type="smallTitle" bold>{english}</Text>&nbsp;&nbsp;&nbsp;
          <Text color="help">{chinese}</Text>
        </div>
      );
    }
  }

  //排序的函数
  objKeySort(obj) {
    var newKey = Object.keys(obj).sort();
    //先用Object 内置类的keys方法获取要排序对象的属性名，再利用Array 原型上的sort方法对获取的属性名进行排序，newKey是一个数组
    var newObj = {};//创建一个新的对象，用于存放排好序的键值对
    for (var i = 0; i < newKey.length; i++) {//遍历newKey数组
      newObj[newKey[i]] = obj[newKey[i]];//向新创建的对象中按照排好的顺序依次增加键值对
    }
    return newObj;//返回排好序的新对象
  }

  onPanelClick(index) {
    let pagesObject = Object.keys(pages);
    let defaultActive = pagesObject[index] === this.state.defaultActive ? '' : pagesObject[index];
    this.setState({
      defaultActive,
    });
  }

  //切换menu
  toggleMenu() {
    let promise = new Promise((resolve, reject) => {
      let showStatus = !this.state.isMenuShow;
      resolve(showStatus);
    })
    promise.then((status) => {
      this.setState({
        isMenuShow: status,
      })
    })
  }

  render() {
    return (
      <div>
        <Header />
        <div className="wrapper-container">
          <div className={["menu-container br-scroll ", this.state.isMenuShow?"menu-translatex":null].join('')}>
            <Accordion onToggle={this.onPanelClick}>
              {
                Object.keys(pages).map(category => {
                  const categoryInfoList = this.objKeySort(pages[category]);
                  const components = Object.keys(categoryInfoList).map((component) => ({name: component, ...categoryInfoList[component]}));
                  return (
                    <Accordion.Panel key={category} active={category === this.state.defaultActive} title={<Text type="title" bold>{category}</Text>}>
                      <ul className="menu-list">
                        {
                          category !== 'REACT' ?
                          (
                            Object.keys(categoryInfoList).map(page => {
                              return this.renderMenuItem(categoryInfoList, page);
                            })
                          )
                          :
                          (
                            Object.keys(componentClassify).map((type) => {
                              const currentTypeComponents = components.filter(component => component.type === type);
                              return (
                                <div className="component-classfify-wrapper" key={type}>
                                  <Text className="component-type">{classify2CN[type]}</Text>
                                  {
                                    currentTypeComponents.map(component => {
                                      return this.renderMenuItem(categoryInfoList, component.name);
                                    })
                                  }
                                </div>
                              )
                            })
                          )
                        }
                      </ul>
                    </Accordion.Panel>
                  )
                })
              }
            </Accordion>
          </div>
          <div className="main-container">
            {this.getComponent(this.state.page)}
          </div>
          {
            this.state.isMenuShow ? <div className="menu-mask" onClick={this.toggleMenu}></div> : ''
          }
        </div>
        {/* {
          this.state.isMenuShow ? <div className="menu-mask" onClick={this.toggleMenu}></div> : ''
        } */}
        <div className="menu-handle" onClick={this.toggleMenu}>
          <i className="menu-handle-icon"></i>
        </div>
      </div>
    )
  }

  renderMenuItem(categoryList, page) {
    return (
      <li key={page} className={`menu-item ${page === this.state.page ? 'active' : ''}`}>
        <a href={`#/${page}`}>{this.dealTitleConfig(categoryList[page].title)}</a>
      </li>
    )
  }
}
